/*
 * author      : 吴中勤 
 * date        : 2018/9/30
 * description : TODO
 */

package com.deepexi.adapter.converter.sap.fund;

import com.deepexi.adapter.facade.moby.request.MobyEventBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Hashtable;

@Service
public class LockService {

    private static final Logger logger = LoggerFactory.getLogger(FundService.class);

    /** 并发控制锁 TODO 如果是多实例部署, 需要使用分布式锁 */
    private static final int LOCK_MAX_SIZE = 1000;
    private static final Object INNER_LOCK = new Object();
    private static final Hashtable<String, Object> syncLock = new Hashtable<>(LOCK_MAX_SIZE);

    /* 同一订单号, 不允许同一时间进行并发支付 */
    public String lockNameOfMobyEvent(MobyEventBody body) {
        return body.getMobyTradeOrder().getId();
    }


    /* 资金同步, 并发控制: 不允许同时支付 同一订单: 消息同时多次 */
    public Object getLock(MobyEventBody body) {
        String lockName = lockNameOfMobyEvent(body);

        synchronized (INNER_LOCK) {
            if (null == syncLock.get(lockName)) {
                syncLock.put(lockName, new Object());
            } else {
                logger.warn("!!! 同一时间,订单号={} 同时发生支付 !!!");
            }
            return syncLock.get(lockName);
        }
    }

    public void releaseLock(MobyEventBody body) {
        syncLock.remove(lockNameOfMobyEvent(body));
    }
}
